using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Unified.payment.code.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;
using System.IO;
using ZXing;
using ZXing.Common;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

namespace Unified.payment.code.Pages
{
    public class UnifiedPaymentModel : PageModel
    {
        private readonly UnifiedPaymentService _paymentService;
        private readonly IConfiguration _configuration;

        public UnifiedPaymentModel(UnifiedPaymentService paymentService, IConfiguration configuration)
        {
            _paymentService = paymentService;
            _configuration = configuration;
        }

        [BindProperty]
        public string WechatPayUrl { get; set; } = "";

        [BindProperty]
        public string AlipayUrl { get; set; } = "";

        [BindProperty]
        public IFormFile? WechatQrCodeFile { get; set; }

        [BindProperty]
        public IFormFile? AlipayQrCodeFile { get; set; }

        public string UnifiedQrCode { get; set; } = "";

        public string ErrorMessage { get; set; } = "";

        public void OnGet()
        {
            // 从配置文件读取默认链接
            WechatPayUrl = _configuration["PaymentUrls:WechatPayUrl"] ?? "wxp://f2f0...";
            AlipayUrl = _configuration["PaymentUrls:AlipayUrl"] ?? "https://qr.alipay.com/...";
        }

        public IActionResult OnPost()
        {
            try
            {
                // 如果上传了微信二维码图片，则从中提取链接
                if (WechatQrCodeFile != null && WechatQrCodeFile.Length > 0)
                {
                    WechatPayUrl = ExtractUrlFromQrCode(WechatQrCodeFile);
                    if (string.IsNullOrEmpty(WechatPayUrl))
                    {
                        ErrorMessage = "无法从微信二维码图片中识别出有效的支付链接";
                        return Page();
                    }
                }

                // 如果上传了支付宝二维码图片，则从中提取链接
                if (AlipayQrCodeFile != null && AlipayQrCodeFile.Length > 0)
                {
                    AlipayUrl = ExtractUrlFromQrCode(AlipayQrCodeFile);
                    if (string.IsNullOrEmpty(AlipayUrl))
                    {
                        ErrorMessage = "无法从支付宝二维码图片中识别出有效的支付链接";
                        return Page();
                    }
                }

                if (string.IsNullOrWhiteSpace(WechatPayUrl) || string.IsNullOrWhiteSpace(AlipayUrl))
                {
                    ErrorMessage = "请填写完整的微信和支付宝支付链接，或上传对应的二维码图片";
                    return Page();
                }

                // 验证链接格式
                if (!IsValidPaymentUrl(WechatPayUrl, "wechat") || !IsValidPaymentUrl(AlipayUrl, "alipay"))
                {
                    ErrorMessage = "支付链接格式不正确";
                    return Page();
                }

                // 生成统一支付二维码
                UnifiedQrCode = _paymentService.GenerateSmartPaymentQrCode(WechatPayUrl, AlipayUrl);
            }
            catch (Exception ex)
            {
                ErrorMessage = $"生成二维码时出错: {ex.Message}";
            }

            return Page();
        }

        private string ExtractUrlFromQrCode(IFormFile qrCodeFile)
        {
            try
            {
                using var stream = qrCodeFile.OpenReadStream();
                using var image = Image.Load<Rgba32>(stream);
                
                // 创建条码读取器，明确指定使用ZXing.ImageSharp中的类型
                var barcodeReader = new ZXing.ImageSharp.BarcodeReader<Rgba32>();
                barcodeReader.Options = new DecodingOptions
                {
                    PossibleFormats = new BarcodeFormat[] { BarcodeFormat.QR_CODE },
                    TryHarder = true
                };
                
                // 解码二维码
                var result = barcodeReader.Decode(image);
                return result?.Text ?? "";
            }
            catch (Exception)
            {
                return "";
            }
        }

        private bool IsValidPaymentUrl(string url, string type)
        {
            if (type == "wechat")
            {
                // 微信支付链接通常以 wxp:// 开头
                return url.StartsWith("wxp://") || url.Contains("weixin.qq.com");
            }
            else if (type == "alipay")
            {
                // 支付宝链接通常包含 alipay.com
                return url.Contains("alipay.com") || url.StartsWith("https://qr.alipay.com/");
            }
            return false;
        }
    }
}